package com.example.lenovo.asia5b.my.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.example.lenovo.asia5b.home.activity.MainActivity;
import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.SMSCode;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import app.BaseFragment;
import fay.frame.ui.U;


/**
 * Created by lenovo on 2017/7/14.
 */

public class UpdatePWDFragment extends BaseFragment implements ICallBack {

    private View view;
    private TimeCount timeCount;
    private long timeOut;
    private EditText actitivy_password_modify_old_password,actitivy_password_modify_new_password,
            actitivy_password_modify_confirm_new_password,activity_register_edit_message;
    private Button activity_password_modify_code,actitivy_password_modify_save;
    private UserBean user;
    private LoadingDalog loadingDalog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.viewpager_update_password,null);
        initView();
        return view;
    }

    public void initView() {
        actitivy_password_modify_old_password = view.findViewById(R.id.actitivy_password_modify_old_password);//旧密码
        actitivy_password_modify_new_password = view.findViewById(R.id.actitivy_password_modify_new_password);//新密码
        actitivy_password_modify_confirm_new_password = view.findViewById(R.id.actitivy_password_modify_confirm_new_password);//确认新密码
        activity_register_edit_message = view.findViewById(R.id.activity_register_edit_message);//验证码
        activity_password_modify_code = view.findViewById(R.id.activity_password_modify_code);
        activity_password_modify_code.setOnClickListener(this);
        actitivy_password_modify_save = view.findViewById(R.id.actitivy_password_modify_save);
        actitivy_password_modify_save.setOnClickListener(this);
        loadingDalog = new LoadingDalog(getActivity());
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.public_btn_left:
                getActivity().finish();
                break;
            case R.id.activity_password_modify_code:
                user = (UserBean) SharedPreferencesUtils.getObjectFromShare("user");
                loadingDalog.show();
                SMSCode.getCode(this,user.mobile_phone);
                break;
            case R.id.actitivy_password_modify_save:
                String code = activity_register_edit_message.getText().toString();//验证码
                if(!TextUtils.isEmpty(code)){
                    if(timeOut <= 1){
                        U.Toast(getActivity(),getResources().getString(R.string.yzmsx));
                    }else{
                        updatePassword(code);
                    }
                }else{
                    U.Toast(getActivity(),getResources().getString(R.string.yzmbnwk));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 保存密码
     */
    private void updatePassword(String code){
        try{
            String oldPWD = actitivy_password_modify_old_password.getText().toString();//旧密码
            String newPWD = actitivy_password_modify_new_password.getText().toString();//新密码
            String confirmNewPWD = actitivy_password_modify_confirm_new_password.getText().toString();//确认新密码
            if(!TextUtils.isEmpty(oldPWD)){
                if(!TextUtils.isEmpty(newPWD)){
                    if(newPWD.length() >= 6){
                        if(!TextUtils.isEmpty(confirmNewPWD)){
                            if(TextUtils.equals(newPWD,confirmNewPWD)){
                                if(!TextUtils.isEmpty(code)){
                                    Date date = new Date();
                                    String updatePWDURL = Setting.UPDATEPASSWORD;
                                    Map<String,String> map = new HashMap<String,String>();
                                    String user_id = user.user_id;
                                    map.put("user_id",user_id);
                                    map.put("used_pass",oldPWD);
                                    map.put("new_pass",newPWD);
                                    map.put("code",code);
                                    String time = String.valueOf(date.getTime());
                                    map.put("time",time);
                                    String[] sortStr = {"user_id"+user_id,"used_pass"+oldPWD,"new_pass"+newPWD,
                                            "code"+code,"time"+time};
                                    String sort = Logic.sortToString(sortStr);
                                    String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sort));
                                    map.put("sign",md5);

                                    JsonTools.getJsonAll(this,updatePWDURL,map,1);
                                }else{
                                    U.Toast(getActivity(),getResources().getString(R.string.yzmbnwk));
                                }
                            }else{
                                U.Toast(getActivity(),getResources().getString(R.string.xmmqrmmbxt));
                            }
                        }else{
                            U.Toast(getActivity(),getResources().getString(R.string.qrxmmbnwk));
                        }
                    }else{
                        U.Toast(getActivity(),getResources().getString(R.string.mmcdbxdy6));
                    }
                }else{
                    U.Toast(getActivity(),getResources().getString(R.string.xmmbnwk));
                }
            }else{
                U.Toast(getActivity(),getResources().getString(R.string.jmmbnwk));
            }
        }catch (Exception e){
            Log.e("修改密码接口Error：",e.getMessage());
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            Intent intent = null;
            try{
                if(result != null){
                    JSONObject jsonObject = (JSONObject)result;
                    if(action == 0){
                        String msgText = jsonObject.getString("MsgText");
                        if("true".equals(msgText)){
                            timeCount = new TimeCount(60000, 1000);
                            timeCount.start();
                            String state = jsonObject.getString("State");
//                            U.Toast(getActivity(),state);
                        }else if("false".equals(msgText)){
                            String state = jsonObject.getString("State");
                            U.Toast(getActivity(),state);
                        }
                        loadingDalog.dismiss();
                    }else if(action == 1){
                        int state = jsonObject.getInt("State");
                        if(state == 0){
                            U.Toast(getActivity(),getResources().getString(R.string.modify_succeed));
                            SharedPreferencesUtils.clear();
                            intent = new Intent(getActivity(), MainActivity.class);
                            startActivity(intent);
                            getActivity().finish();
                        }  else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(getActivity(), getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(getActivity(), getResources().getString(R.string.mysj));
                        }else if(state == 4){
                            U.Toast(getActivity(),getResources().getString(R.string.mmcdbxdy6));
                        }else if(state == 5){
                            U.Toast(getActivity(),getResources().getString(R.string.sjyzmcw));
                        }else if(state == 6){
                            U.Toast(getActivity(),getResources().getString(R.string.ymmcw));
                        }else if(state == 7){
                            U.Toast(getActivity(),getResources().getString(R.string.xjmmbnyz));
                        }else if(state == 15){
                            U.Toast(getActivity(),getResources().getString(R.string.yzmsx));
                        }
                    }
                }else{
//                U.Toast(getActivity(),"服务器连接失败"+result);
                }
            }catch (Exception e){
                Log.e("修改密码JSONError：",e.getMessage());
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 获取验证码倒计时
     */
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (null == getActivity()) {
                return;
            }
            if(null == activity_password_modify_code) {
                return;
            }
            activity_password_modify_code.setClickable(false);
            timeOut = millisUntilFinished / 1000;
            activity_password_modify_code.setText((getResources().getString(R.string.message_has_been_sent)+"(" + timeOut + ")"));
        }

        @Override
        public void onFinish() {
            activity_password_modify_code.setText(getResources().getString(R.string.to_obtain_the_verification_code));
            activity_password_modify_code.setClickable(true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != timeCount) {
            timeCount.cancel();
        }
    }
}
